#include "my_stdio.h"
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

mFILE *mfopen(const char *filename, const char *mode)
{
    int fd = -1;
    if(strcmp(mode, "r") == 0)
    {
        fd = open(filename, O_RDONLY);
    }
    else if(strcmp(mode, "w")== 0)
    {
        fd = open(filename, O_CREAT|O_WRONLY|O_TRUNC, 0666);
    }
    else if(strcmp(mode, "a") == 0)
    {
        fd = open(filename, O_CREAT|O_WRONLY|O_APPEND, 0666);
    }
    if(fd < 0) return NULL;
    mFILE *mf = (mFILE*)malloc(sizeof(mFILE));
    if(!mf) 
    {
        close(fd);
        return NULL;
    }

    mf->fileno = fd;//文件描述符
    mf->flag = FLUSH_LINE;//刷新状态
    mf->size = 0;//初始化缓冲区大小
    mf->cap = SIZE;//缓冲区容量

    return mf;
}

void mfflush(mFILE *stream)
{
    if(stream->size > 0)  // 1. 检查是否有数据需要刷新
    {
        // 2. 将用户缓冲区数据写入内核缓冲区
        write(stream->fileno, stream->outbuffer, stream->size);
        
        // 3. 强制将内核缓冲区数据写入物理设备
        fsync(stream->fileno);
        
        // 4. 重置缓冲区状态
        stream->size = 0;
    }
}

int mfwrite(const void *ptr, int num, mFILE *stream)
{
    // 1. 拷贝
    memcpy(stream->outbuffer+stream->size, ptr, num);
    stream->size += num;

    // 2. 检测是否要刷新
    if(stream->flag == FLUSH_LINE && stream->size > 0 && stream->outbuffer[stream->size-1]== '\n')
    {
        mfflush(stream);
    }
    return num;
}

void mfclose(mFILE *stream)
{
    if(stream->size > 0)
    {
        mfflush(stream);
    }
    close(stream->fileno);
}
